class PurchaseItem < ActiveRecord::Base
  attr_accessible :product_id, :purchase_id, :quantity, :size_id
  
  belongs_to :purchase
  belongs_to :product  
  belongs_to :size
  
  
  validates_presence_of :product_id, :size_id,  :quantity
  validates :quantity, :numericality => { :greater_than => 1 }
   
  validate :has_enough_stock
  
  private
  
  # check if item exist and have enough stock available
  def has_enough_stock
    puts "start to check stock..................."
    item = Stock.where("size_id=? and product_id=?", self.size_id, self.product_id).first
      
    if ( item.nil? ) 
      errors.add(:size_id,"Item "+self.product.item_number + " with " +self.size.name.to_s  +  " does not exists!")    
    end    
  end 
end
